#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#define N 1000000000

int NUM_THREADS = 4;

const unsigned int A = 1664525, C = 1013904223;

unsigned int next(unsigned int x)
{
          return x*A+C;
}

void *montecarlo(void *args) {
  double x, y;
  int i, M, tmp = 0;
  unsigned int r = time(NULL);
  void *dots = malloc(sizeof(int));
  int *dots_inside_circle = (int *) dots;
  M = N/NUM_THREADS;
  for (i=0; i<M; i++) {
    r = next(r);
    x = (r%1000)/1000.0;        
    r = next(r);
    y = (r%1000)/1000.0;        
    if ( x*x + y*y < 1.0 )
      tmp++;
  }
  *dots_inside_circle = tmp;
  pthread_exit((void *) dots);
}

int main(int argc, char *argv[]) {
  if (argc == 2)
    NUM_THREADS = atoi(argv[1]);
  srand(time(NULL));
  pthread_t threads[NUM_THREADS];
  int i, dots_inside_circle = 0, *p;
  void *status;
  for(i=0; i<NUM_THREADS; i++) {
    pthread_create(&threads[i], NULL, montecarlo, NULL);    
  }
  for(i=0; i<NUM_THREADS; i++) {
    pthread_join(threads[i], &status);
    p = (int *) status;
    dots_inside_circle += (*p);
  }
  printf("%.6lf\n", 4.0*(1.0*dots_inside_circle/N));
  return 0;  
}
